var express=require('express')
var Router=express.Router()

var redis=require('../../tools/redis/index.js')
var db=require('../../tools/database/index.js')

Router.get('/client/login',async (req,res)=>{
	 var query=req.query
	 var name=query.name||null
	 var password=query.password||null;
	 var ip=req.headers['origin']||Math.random();
	 var key=name;
	 // conso
	 function  callback(parms){
		 parms=JSON.stringify(parms)
		 if(req.query.callback){
			 return `${req.query.callback}(${parms})`
		 }else{
			return parms;
		 }
	 }
	 var history=await redis.get(key+password+ip)
	 //检查是否登陆
	 if(history!=null){
			res.send(callback({
				state:200,
				data:history
		  }))
	 }else{
		 var d=db.clients.query({
		 		 name:name,
		 		 password:password
		 }).then(
		 		success=>{
					if(!success){
						res.send({
							state:404,
							msg:'用户或密码错误'
						})
					return;
					}
					key= '<client>' 
							 +'-'
							 +key
							 +'-'
							 +password
							 +'-'
							 +success._id
							 +'-'
							 +ip||Math.random();
		 			redis.set(key,key).then(
		 				result=>{
		 					res.send(callback({
		 						state:200,
		 						data:result
		 					}))
		 				},
						err=>{
							res.send({
								state:400
							});
						}
		 			)
		 		},
		 		error=>{
		 			res.send({
		 				state:404
		 			});
		 		}
		 )
	 }
 })
 
module.exports=Router